// 289.生命游戏
package Leetcode;

class Solution_289 {
    public void gameOfLife(int[][] board) {
        int m = board.length;
        int n = board[0].length;

        int[][] neighbour = new int[m][n];
        for (int i = 0; i < m; i++)
            for (int j = 0; j < n; j++) {
                neighbour[i][j] = count(board, i, j);
            }

        for (int i = 0; i < m; i++)
            for (int j = 0; j < n; j++) {
                if (board[i][j] == 1 && (neighbour[i][j] < 2 || neighbour[i][j] > 3))
                    board[i][j] = 0;
                else if (board[i][j] == 0 && neighbour[i][j] == 3)
                    board[i][j] = 1;
            }
    }

    // 计算周围八格有几个活细胞
    public int count(int[][] board, int index_x, int index_y) {
        int result = 0;
        for (int i = index_x - 1; i <= index_x + 1; i++) {
            for (int j = index_y - 1; j <= index_y + 1; j++) {
                if (i == index_x && j == index_y)
                    continue;
                if (i < 0 || j < 0 || i == board.length || j == board[0].length)
                    continue;
                result += board[i][j];
            }
        }
        return result;
    }
}